package qf.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import qf.dao.GoodsDao;
import qf.dao.daoImpl.GoodsDaoImpl;
import qf.pojo.Goods;
import qf.service.GoodsService;
import qf.service.serviceImpl.GoodsServiceImpl;
import qf.utils.Constants;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author 86198
 * @version V1.0
 * @Project Java_qf
 * @Package qf.controller
 * @Description:
 * @Date 2022/5/24 19:18
 */
@WebServlet("/goods")
public class GoodsController extends BaseServlet{
    /**
     * 用户登录后跳转到主页并输出数据
     * @param request
     * @param response
     * @return
     */
    public String index(HttpServletRequest request, HttpServletResponse response){

        GoodsDao goodsDao = new GoodsDaoImpl();
        GoodsService goodsService = new GoodsServiceImpl(goodsDao);

        List<Goods> goods = goodsService.showGoods();
        System.out.println(goods);
        request.setAttribute("goodsList",goods);
        return  Constants.FORWARD+"/index.jsp";


    }
    /**
     * 展示所有商品
     * @param request
     * @param response
     * @return
     */
    public String show(HttpServletRequest request, HttpServletResponse response){
        GoodsDao goodsDao = new GoodsDaoImpl();
        GoodsService goodsService = new GoodsServiceImpl(goodsDao);

        List<Goods> goods = goodsService.showGoods();
        System.out.println(goods);
        request.setAttribute("goodsList", goods);
        return Constants.FORWARD +"/admin/showGoods.jsp";
    }

    public String addGoods(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //1.创建文件解析工厂对象
    DiskFileItemFactory factory = new DiskFileItemFactory();

    //2.从工厂中获取解析器对象
        ServletFileUpload parser = new ServletFileUpload(factory);
    //3.解决文件名乱码问题
        parser.setHeaderEncoding("utf-8");
     //4.判断上传的表单类型，如果表单类型中带   enctype="multipart/form-data" 说明是有上传文件
        if (!ServletFileUpload.isMultipartContent(request)) {
            return "redirect:/admin/admin.jsp";
        }


    //5.调用解析器上传的数据
        List<FileItem> fileItems = parser.parseRequest(request);
    //6.获取保存文件的本地服务其目录路径
    //上传到项目编译后的路径位置：例如：E:\JavaIdea\Java_qf\out\artifacts\Myshop2203_war_exploded\files
            String uploadPath = request.getServletContext().getRealPath("/files");
    //7.判断服务器保存文件目  录是否存在，如果目录不存在在自动创建文件夹
            File fileDir = new File(uploadPath);
            //判断  "/files" 是否有此文件夹
            if (!fileDir.exists()) {
                //如果没有自动创建
                fileDir.mkdirs();
            }
    //8.创建Goods商品对象
            Goods goods = new Goods();
   //9.遍历表单中的每一个元素
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {
    //10. 判断如果是普通表单, 将表单数据存入Goods商品对象中
                    if (fileItem.getString() == null || "".equals(fileItem.getString())) {
                        continue;
                    }
               //如果是商品  分类放入goods对象中
                    if ("typeid".equals(fileItem.getFieldName())) {
                        goods.setTid(Integer.parseInt(fileItem.getString()));
                    }
                //商品名称
                    if ("name".equals(fileItem.getFieldName())) {
                        goods.setName(new String(fileItem.getString().getBytes("ISO-8859-1"),"utf-8"));
                    }
                    //商品创建时间
                    if ("pubdate".equals(fileItem.getFieldName())) {
                        String dateStr = fileItem.getString();
                        //日期格式化
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        goods.setPubdate(sdf.parse(dateStr));
                    }
                    //商品价格
                    if ("price".equals(fileItem.getFieldName())) {
                        goods.setPrice(Integer.parseInt(fileItem.getString()));
                    }
                    //商品评分
                    if ("star".equals(fileItem.getFieldName())) {
                        goods.setStar(Integer.parseInt(fileItem.getString()));
                    }
                    //商品简介
                    if ("intro".equals(fileItem.getFieldName())) {
                        goods.setIntro(new String(fileItem.getString().getBytes("ISO-8859-1")));
                    }
                    }else {
                //11.判断如果是文件，则获取上传文件的路径和文件名
                        String filePath = fileItem.getName();
               //12.如果未上传文件，继续处理下一个字段
                        if (filePath == null || "".equals(filePath)) {
                            continue;
                        }
               //13.获取上传文件的文件名
                        String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);

                //14.做io操作，保存文件到服务器硬盘的指定位置，获取输入流读取文件
                        InputStream inputStream = fileItem.getInputStream();
                //15.将文件保存再服务器硬盘目录 + 文件名，组成具体的保存路径
                        FileOutputStream out = new FileOutputStream(uploadPath + "\\" + fileName);
                        System.out.println("===文件保存后的完整路径===" + uploadPath + "\\" + fileName);
                //创建缓存区
                        byte[] bytes = new byte[1024];
                        //读取的长度
                        int length = 0;
                        //如果读取的长度大于0，说明读取出来内容了，可以输出
                        while ((length=inputStream.read(bytes))>0){
                            out.write(bytes,0,length);
                        }
                        out.close();
                        inputStream.close();
                //16.保存后设置Goods商品对象中图片保存后的路径以及文件名信息
                        //http://localhost:8080/files/xxx.jpg
                        goods.setPicture("http://localhost:8080/files/" + fileName);
                    }

                }


        //17.调用service，保存goods商品对象到数据库的商品表中
        GoodsServiceImpl goodsService = new GoodsServiceImpl(new GoodsDaoImpl());
        goodsService.addGoods(goods);

        //18. 跳转到商品查看页面
        return "redirect:/admin/showGoods.jsp";
}

    /**
     * 页面点击进入商品详情页面
     * @param request
     * @param response
     * @return
     */
    public String detail(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        System.out.println(id);
        //根据查询商品id将数据传到前端页面
        GoodsDao goodsDao = new GoodsDaoImpl();
        GoodsService goodsService = new GoodsServiceImpl(goodsDao);
        Goods goods = goodsService.selectGoodsBYID(Integer.parseInt(id));

        //将商品数据放到域中并转发
        request.setAttribute("goods",goods);

        return  Constants.FORWARD+"/goodsDetail.jsp";
    }

}
